import { BiliWEBSocketClient, BiliWSSOperationCode } from "@/tool/BiliWEBSocketClient"
import { StreamRead } from "@/tool/stringUtils"
import { RoomInfoType } from "@/types/types"
import { ref } from "vue"
import { operator } from "./operator"
import { endRoomModule, isstart } from '@/module/room'
import { ElMessage } from "element-plus"

const client = ref()
const timer = ref()

export function openSSW (roomInfo: RoomInfoType,  index: number = 0){
  if(index > roomInfo.websocket_info.wss_link.length 
          || roomInfo.websocket_info.wss_link.length == 0){
      console.error("[Socket] 长度非法")
  }
  else {
    client.value = new BiliWEBSocketClient(roomInfo.websocket_info.wss_link[index]);

    client.value.onopen = () => {
      handing(roomInfo)
      timer.value = setInterval(() => {
          heartbeating()
      }, 20000)
      console.log("[Socket] open success")
    }

    client.value.onmessage = (msg: any) => {
      onMessage(msg)
    }
    client.value.onclose = () => {
      console.log("[Socket] close socket")
      endRoomModule()
      ElMessage({
        message: 'WebSocket连接已关闭',
        type: 'success',
      })
    }
  }
}

export function closeSSW (){
    clearInterval(timer.value)
    client.value.close()
}

export function packageRead(responseMsg: any, responseOperator: any) {
  if(responseOperator == BiliWSSOperationCode.OP_AUTH_REPLY){
    console.log("[Socket_Back] hand success")
    isstart.value = true
    
    ElMessage({
      message: '连接成功',
      type: 'success',
    })
  }
  //心跳回复包
  else if(responseOperator == BiliWSSOperationCode.OP_HEARTBEAT_REPLY){
    console.log("[Socket_Back] heartbeat success")
  }
  else if(responseOperator == BiliWSSOperationCode.OP_SEND_SMS_REPLY){
    operator(responseMsg)
  }
}

function handing(data: RoomInfoType) {
  client.value.sendMsg(BiliWSSOperationCode.OP_AUTH, data.websocket_info.auth_body)
}
function heartbeating() {
  client.value.sendMsg(BiliWSSOperationCode.OP_HEARTBEAT)
}

function onMessage(msg: any) {
  let result = StreamRead(msg)
}

